<!-- 摄像头 -->
<script setup lang='ts'>
import { ref } from 'vue';
// import { ElMessage } from 'element-plus'

const video = ref<HTMLVideoElement>();
const cvs = ref<HTMLCanvasElement>();
let recoder: any = null;


// 打开摄像头
let streamSX: any;
const startVideo = async () => {
  // return console.log(video)
  navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
    streamSX = stream;
    ElMessage.success('开启摄像头成功');
    video.value!.srcObject = stream;
  }).catch((err) => {
    console.log(err);
    ElMessage.error('开启摄像头失败' + err);
  });
};

// 拍照
const photograph = () => {
  cvs.value!.getContext('2d')!.drawImage(video.value!, 0, 0, cvs.value!.width, cvs.value!.height);
};

// 关闭摄像头
const closeVideo = () => {
  streamSX.getTracks().forEach((track: any) => track.stop());
};

// 摄像
const mutedVideo = ref(false);
let videoData: any[] = [];
const pictureRecording = () => {
  mutedVideo.value = true;
  navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((stream) => {
    video.value!.srcObject = stream;
    recoder = new MediaRecorder(stream);
    recoder.ondataavailable = (e: any) => {
      videoData.push(e.data);
    };
    // 下载视频
    recoder.onstop = (_e: any) => {
      stream.getTracks().forEach((track: any) => track.stop());

      const blob = new Blob(videoData, { type: recoder.mimeType });

      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = new Date().getTime() + 'video.webm';
      link.click();
      // 释放链接
      URL.revokeObjectURL(url);
      link.remove();
    };
    recoder.start();
  });
};

// 停止摄像
const closePictureRecording = () => {
  recoder.stop();
  videoData = [];
};
</script>

<template>
  <div>
    <video width="640" height="480" autoplay :muted="mutedVideo" ref="video"></video>
    <div>
      <el-button type="primary" round @click="startVideo()">开启摄像头</el-button>
      <el-button type="primary" round @click="photograph()">拍照</el-button>
      <el-button type="primary" round @click="closeVideo()">关闭摄像头</el-button>
      <el-button type="primary" round @click="pictureRecording()">开始录像</el-button>
      <el-button type="primary" round @click="closePictureRecording()">停止录像</el-button>
    </div>
    <canvas width="640" height="480" ref="cvs">
      该浏览器暂不支持canvas，请升级或更换浏览器！
    </canvas>
  </div>
</template>

<style lang='scss' scoped></style>